package cn.innosmart.aq.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.tutk.p2p.ConnectionManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.WorkLogTempListAdapter;
import cn.innosmart.aq.bean.WorkLogTemp;
import cn.innosmart.aq.util.INetworkInteractUtil;
import cn.innosmart.aq.util.NetworkInteractUtil;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.view.activity.base.BaseActivity;

/**
 * Created by David on 2015/12/1.
 */
public class WorkLogActivity extends BaseActivity implements INetworkInteractUtil {
    private final int EXIT = 0;
    private final int LOADINGDATA = 1;
    private Toolbar toolbar;
    private ListView lvWorkLog;
    private WorkLogTempListAdapter workLogListAdapter;
    private NetworkInteractUtil interactUtil;
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.rl_add:
                    Intent intents = new Intent(WorkLogActivity.this, WorkLogTempChooseActivity.class);
                    startActivityForResult(intents, 1001);
                    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    finish();
                    break;
                case R.id.tv_delete:
                    loadingDialog();
                    WorkLogTemp workLogDelete = (WorkLogTemp) v.getTag();
                    JSONObject jsonParam = new JSONObject();
                    try {
                        jsonParam.put("id", workLogDelete.getId());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    interactUtil.removeWorkLogTemp(jsonParam);
                    break;
                case R.id.rl_data:
                    WorkLogTemp workLogs = (WorkLogTemp) v.getTag();
                    Intent listIntent = new Intent(WorkLogActivity.this, WorkLogListActivity.class);
                    listIntent.putExtra("worklog", workLogs.toJSonObject().toString());
                    startActivity(listIntent);
                    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    break;
            }

        }
    };
    private Menu menu;
    public static ArrayList<WorkLogTemp> workLogs;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EXIT:
                    exit();
                    break;
                case LOADINGDATA:
                    workLogs = (ArrayList<WorkLogTemp>) msg.obj;
                    workLogListAdapter = new WorkLogTempListAdapter(WorkLogActivity.this, workLogs);
                    workLogListAdapter.setOnItemClickListener(onClickListener);
                    lvWorkLog.setAdapter(workLogListAdapter);
                    if (workLogs.size() != 0) {
                        menu.findItem(R.id.action_edit).setVisible(true);
                    } else {
                        menu.findItem(R.id.action_edit).setVisible(false);
                    }
                    hideloadingDialog();
                    break;
            }
        }
    };
    private boolean isModify;
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            String msg = "";
            switch (menuItem.getItemId()) {
                case R.id.action_edit:
                    isModify = !isModify;
                    if (isModify) {
                        menuItem.setTitle(R.string.action_exit_edit);
                    } else {
                        menuItem.setTitle(R.string.edit_temp);
                    }
                    if (workLogListAdapter != null)
                        workLogListAdapter.startModify(isModify);
                    break;
            }
            return true;
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == 1001) {
            String str = SharedUtil.getInstance().readWorkLog(ConnectionManager.getInstance().getCurrentConnectionEntity().getUid());
            try {
                JSONObject jsonWorkLogs = new JSONObject(str);
                JSONArray jsonArray = jsonWorkLogs.getJSONArray("column");
                ArrayList<WorkLogTemp> workLogs = new ArrayList<>();
                for (int i = 0; i < jsonArray.length(); i++) {
                    WorkLogTemp workLog = new WorkLogTemp(jsonArray.getJSONObject(i));
                    workLogs.add(workLog);
                }
                hideloadingDialog();
                workLogListAdapter.refresh(workLogs);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_log);
        setBar();
        initView();
        interactUtil = new NetworkInteractUtil(this);
        loadingDialog();
        interactUtil.getWorkLogTemp();
    }

    private void initView() {
        lvWorkLog = (ListView) findViewById(R.id.ll_work_log);
    }

    private void setBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("");
        TextView tv = (TextView) toolbar.findViewById(R.id.tv_toolbar);
        tv.setText(R.string.activity_work_log_title);
        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHandler.sendEmptyMessage(EXIT);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        toolbar.setNavigationIcon(null);
    }
    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        getMenuInflater().inflate(R.menu.menu_work_log_edit, menu);
        this.menu = menu;
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onNetworkInteractAllOver(int ret) {

    }

    @Override
    public void onNetworkInteractOver(int ret, String flag, Object object) {
        if (flag.equals(interactUtil.GETWORKLOGTEMP)) {
            hideloadingDialog();
            ArrayList<WorkLogTemp> workLogs = new ArrayList<>();
            if (ret == 0) {
                JSONArray jsonArray = (JSONArray) object;
                JSONObject jsonParams = null;
                System.out.println("jsonArray=" + jsonArray.toString());
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {
                        jsonParams = new JSONObject(jsonArray.getString(i));
                        JSONObject jsonWorkLogs = new JSONObject(jsonParams.getString("property"));
                        WorkLogTemp workLog = new WorkLogTemp(jsonWorkLogs);
                        workLog.setId(jsonParams.getString("id"));
                        workLogs.add(workLog);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } else {

            }
            Message msg = mHandler.obtainMessage();
            msg.what = LOADINGDATA;
            msg.obj = workLogs;
            mHandler.sendMessage(msg);
        } else if (interactUtil.REMOVEWORKLOGTEMP.equals(flag)) {
            if (ret == 0) {
                JSONObject jsonObject = (JSONObject) object;
                System.out.println("jsonObkect=" + jsonObject);
                try {
                    String id = jsonObject.getString("id");
                    workLogListAdapter.remove(id);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
            }
            if (workLogListAdapter.getCount() == 1) {
                menu.findItem(R.id.action_edit).setVisible(false);
            } else {
                menu.findItem(R.id.action_edit).setVisible(true);

            }
            hideloadingDialog();
        }
    }
}
